//
//  TCM_LoginViewController.swift
//  TCM_TradingProject
//
//  Created by 吕春海 on 2018/8/14.
//  Copyright © 2018年 lvchunhai. All rights reserved.
//

import UIKit
import TextFieldEffects
import RxSwift
import RxCocoa
import IQKeyboardManagerSwift
import SnapKit
import Toaster

class TCM_LoginViewController: TCM_BaseViewController,UITextFieldDelegate {
    
    var accountStr: String?
    var passwordStr: String?
    var isShowPassword: Bool!
    var isUpdataExpand: Bool!
    let disposeBag = DisposeBag()
    
    @IBOutlet weak var iconImageView: UIImageView!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var pwdTF: AkiraTextField!
    @IBOutlet weak var accountTF: AkiraTextField!
    @IBOutlet weak var accountImageView: UIImageView!
    @IBOutlet weak var showPwdButton: UIButton!
    @IBOutlet weak var registeredButton: UIButton!
    @IBOutlet weak var remberPwd: UIButton!
    @IBOutlet weak var infoView: UIView!
    @IBOutlet weak var iconTopConstraint: NSLayoutConstraint!
    @IBOutlet weak var infoTopConstraint: NSLayoutConstraint!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "登录"
        initialUI()
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super .viewWillAppear(animated)
        // 键盘将要弹出
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        // 键盘将要回弹
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super .viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)

    }
    
    
    func initialUI() {
        loginButton.layer.cornerRadius = 4
        loginButton.clipsToBounds = true
        isShowPassword = false
        isUpdataExpand = false
        
        self.accountTF.text = TCM_GetUserDefault("accountStr") as? String
        //隐藏IQ键盘的工具条
        IQKeyboardManager.shared.enableAutoToolbar = false
        
        textFieldInput()
        buttonClick()
    }
    
    func textFieldInput() {
        accountTF.rx.text.orEmpty.asObservable()
            .subscribe(onNext: { [weak self] in
                
                self?.changeplaceholderFont(textField: (self?.accountTF)!)
                
                self?.accountStr = $0
                if  (self?.accountStr?.count)! >= 11 {
                    self?.accountImageView.image = UIImage(named: "TCM_LoginAccountOK")
                    self?.accountImageView.isHidden = false
                    self?.accountTF.textMaxLength = 11
                } else {
                    self?.accountImageView.image = UIImage(named: "")
                    self?.accountImageView.isHidden = true
                }
                self?.showButton()
            })
            .disposed(by: disposeBag)
        
        pwdTF.rx.text.orEmpty.asObservable()
            .subscribe(onNext: { [weak self] in
                self?.changeplaceholderFont(textField: (self?.pwdTF)!)
                
                self?.passwordStr = $0
                self?.showButton()
                if (self?.passwordStr?.count)! > 0 {
                    self?.showPwdButton.isHidden = false
                    
                } else {
                    self?.showPwdButton.isHidden = true
                }
            })
            .disposed(by: disposeBag)
    }
    
    func buttonClick() {
        //登录按钮
        loginButton.rx.tap
            .bind{ [weak self] in
                self?.accountTF.resignFirstResponder()
                self?.pwdTF.resignFirstResponder()
                if (self?.accountTF.text?.isAccount())! {
                    if (self?.pwdTF.text?.isPassword(minNumber: 6, maxNumber: 16))! {
                        Toast(text: "登陆成功").show()
                        TCM_SaveUserDefault((self?.accountTF.text)!, "accountStr")
                    } else {
                        Toast(text: "密码应为6-16位的数字与字母的组合").show()
                    }
                } else {
                    Toast(text: "请输入正确的账号").show()
                }
            }
            .disposed(by: disposeBag)
        
        //跳转注册
        registeredButton.rx.tap
            .bind{ [weak self] in
                self?.accountTF.resignFirstResponder()
                self?.pwdTF.resignFirstResponder()
                let registerVC = tcm_registeredViewController()
                registerVC.pageShowType = .pageTypeRegister
                self?.navigationController?.pushViewController(registerVC, animated: true)
            }
            .disposed(by: disposeBag)
        
        //跳转忘记密码
        remberPwd.rx.tap
            .bind{ [weak self] in
                self?.accountTF.resignFirstResponder()
                self?.pwdTF.resignFirstResponder()
                let registerVC = tcm_registeredViewController()
                registerVC.pageShowType = .pageTypeForget
                self?.navigationController?.pushViewController(registerVC, animated: true)
            }
            .disposed(by: disposeBag)
        
        //密文明文切换
        showPwdButton.rx.tap
            .bind{ [weak self] in
                if self?.isShowPassword == false {
                    self?.showPwdButton.setImage(UIImage(named: "TCM_LoginPwdShow"), for: .normal)
                    self?.pwdTF.isSecureTextEntry = false
                    self?.isShowPassword = true
                } else {
                    self?.showPwdButton.setImage(UIImage(named:"TCM_LoginPwdHidden"), for: .normal)
                    self?.pwdTF.isSecureTextEntry = true
                    self?.isShowPassword = false
                }
                
            }
            .disposed(by: disposeBag)
    }
    
    //修改输入/非输入的placeholder字体大小
    func changeplaceholderFont(textField: AkiraTextField) {
        if textField.isFirstResponder || (textField.text?.isEmpty)! == false {
            textField.placeholderFontScale = 0.875
        } else {
            textField.placeholderFontScale = 1
        }
    }
    
    //登录按钮现实逻辑
    func showButton() {
        if  (self.pwdTF.text?.count)! >= 6 && (self.accountTF.text?.count)! >= 11 {
            self.loginButton.isEnabled = true
            self.loginButton.alpha = 1
        } else {
            self.loginButton.isEnabled = false
            self.loginButton.alpha = 0.4
        }
    }
    // MARK: - 键盘将要弹出
    @objc func keyboardWillShow(notification: Notification) {
        let userInfo = notification.userInfo
        let aValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey]
        
        // 判断是否是第一次触发开始编辑，如果是第一次则改变约束
        if isUpdataExpand == false {
            updateWithExpand(isExpanded: true, animated: true, duration: aValue! as! TimeInterval)
            isUpdataExpand = true
        }
    }
    
    // MARK: - 键盘将要回收
    @objc func keyboardWillHide(notification: Notification) {
        let userInfo = notification.userInfo
        let aValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey]
        updateWithExpand(isExpanded: false, animated: true, duration: aValue! as! TimeInterval)
        // 回收把isUpdataExpand设置为false
        isUpdataExpand = false
    }
 
    // MARK: - 更新约束
    func updateWithExpand(isExpanded:Bool, animated:Bool, duration:TimeInterval = 1) {
        // 重要：更新约束需要调用updateConstraints闭包
        if isExpanded == false {
            self.iconTopConstraint.constant = 84
        } else {
            self.iconTopConstraint.constant = 44
        }
        if isExpanded == false {
            self.infoTopConstraint.constant = 63
        } else {
            self.infoTopConstraint.constant = 29
        }
        
        
        
        if animated == true {
            // 告诉self.view约束需要更新
            self.view.needsUpdateConstraints()
            // 调用此方法告诉self.view检测是否需要更新约束，若需要则更新，下面添加动画效果才起作用
            self.view.updateConstraintsIfNeeded()
            // 更新动画
            UIView.animate(withDuration: duration, animations: {
                self.view.layoutIfNeeded()
            })
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
